import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 1.4
import QtQuick.Layouts 1.3
import com.RspInterface 1.0

Item {
    property var acctNo: ""
    property var tabName
    //    property string colon: ":"
    //客户信息
    property RspInterface custDetail2
    //试算结果
    property RspInterface tryCalcRisk
    //未全部成交的强平单
    property RspInterface covOrderRsp

    //    property int rMargin: 110
    //    property bool bInit: false
    property int rand: Math.random()
    onAcctNoChanged: {
        custDetail2 = g_MainQuo.getCustDetail(acctNo)
        freshFundRisk()
        queryCovOrder()
        if (custDetail2.get("acct_no") === "" && acctNo != "") {
            tipInput.text = g_MainQuo.getPopMsg()
            tipInput.open()
        }
    }
    ColumnLayout {
        anchors.fill: parent
        TabView {
            id: custInfo
            anchors.left: parent.left
            anchors.leftMargin: 10
            anchors.top: parent.top
            anchors.topMargin: 5
            anchors.right: parent.right
            anchors.rightMargin: 120
            anchors.bottom: forceOrderGroup.top
            anchors.bottomMargin: 5
            Layout.preferredHeight: 180
            Tab {
                title: "资金与风险信息"

                CustDetail {
                    custDetail: custDetail2
                }
            }
            Tab {
                title: "库存与持仓信息"
                StorePosi {
                }
            }
            Tab {
                title: "未全部成交的平仓单"
                PartMatchCovOrder {
                    //                    have_cust: true
                }
            }
            //            Component.onCompleted: {
            //                currentIndex = 1
            //            }
        }
        Button {
            id: qryBtn
            anchors.top: parent.top
            anchors.topMargin: custInfo.height / 2
            anchors.right: parent.right
            anchors.rightMargin: 20
            text: "刷新"
            onClicked: {
                if (acctNo !== null) {
                    custDetail2 = null
                    custDetail2 = g_MainQuo.getCustDetail(acctNo)
                    freshFundRisk()
                    queryCovOrder()
                }
            }
        }

        GroupBox {
            id: forceOrderGroup
            Layout.fillHeight: true
            anchors.left: parent.left
            anchors.leftMargin: 10
            anchors.right: parent.right
            anchors.rightMargin: 10
            ColumnLayout {
                anchors.fill: parent
                RowLayout {
                    anchors.left: parent.left
                    anchors.leftMargin: 10
                    anchors.right: parent.right
                    anchors.rightMargin: 10
                    anchors.top: parent.top
                    Text {
                        text: "客户号:"
                    }
                    TextField {
                        Layout.preferredWidth: 85
                        id: acct_No
                        text: acctNo
                        placeholderText: "客户号+Enter"
                        onAccepted: {
                            //                            custDetail2 = g_MainQuo.getCustDetail(acct_No.text)
                            //                            console.log("查询：" + acct_No.text + " branch:" + custDetail2.get(
                            //                                            "branch_id"))
                            //                            freshFundRisk()
                            acctNo = acct_No.text
                        }
                    }
                    Text {
                        text: "合约:"
                    }

                    ComboBox {
                        id: prod_Code
                        Layout.preferredWidth: 80
                        model: prodModel

                        onCurrentIndexChanged: freshCovBuySell()
                        //                        onModelChanged: {
                        //                            console.log("onModelChanged:" + prod_Code.currentText)
                        //                        }
                    }
                    Text {
                        text: "买卖:"
                    }

                    ComboBox {
                        id: cov_Posi
                        Layout.preferredWidth: 80
                        model: covDirModel
                    }
                    Text {
                        text: "价格:"
                    }
                    TextField {
                        id: cov_Price
                        Layout.preferredWidth: 60
                        validator: RegExpValidator {
                            regExp: /[0-9.]+/
                        }
                    }
                    Text {
                        text: "数量:"
                    }
                    TextField {
                        id: cov_Volumn
                        Layout.preferredWidth: 50
                        validator: RegExpValidator {
                            regExp: /\d{1,6}/
                        }
                    }
                    Item {
                        Layout.fillWidth: true
                    }
                    Button {
                        text: "生成强平单"
                        onClicked: {
                            if (acct_No.text.trim() === "") {
                                tipInput.text = "请输入客户号"
                                tipInput.open()
                            } else if (cov_Price.text.trim() === "") {
                                tipInput.text = "请输入价格"
                                tipInput.open()
                            } else if (cov_Volumn.text.trim() === "") {
                                tipInput.text = "请输入数量"
                                tipInput.open()
                            } else if (acct_No.text.trim() !== acctNo) {
                                tipInput.text = "客户号已经修改，请先刷新页面"
                                tipInput.open()
                            } else {
                                orderMgr.fOrderModel.append({
                                                                read_send: true,
                                                                create_id: createID(8),
                                                                prod_code: prod_Code.currentText,
                                                                sale_type: cov_Posi.currentText,
                                                                price: cov_Price.text,
                                                                order_state: "未发送",
                                                                remain_amount: "",
                                                                order_id: "",
                                                                local_order_no: "",
                                                                sys_no: "",
                                                                info: "",
                                                                acct_no: acctNo,
                                                                amount: cov_Volumn.text
                                                            })
                                orderMgr.checkRowChange(-2, false)
                            }
                        }
                    }
                    Item {
                        Layout.preferredWidth: 10
                    }
                }

                ForceOrderMgr {
                    id: orderMgr
                    anchors.bottom: parent.bottom
                    anchors.left: parent.left
                    anchors.right: parent.right
                    anchors.rightMargin: 5
                    anchors.top: parent.top
                    anchors.topMargin: 30
                    Layout.fillHeight: true

                    onCheckRowChange: {
                        console.log("onCheckRowChange:" + row + " bcheck:" + bCheck)
                        if (row >= 0) {
                            //单个勾选的处理
                            fOrderModel.get(row).read_send = bCheck
                        }

                        //平仓试算
                        var close_para = ""
                        for (var k = 0; k < fOrderModel.count; k++) {
                            if (!fOrderModel.get(k).read_send)
                                continue

                            close_para += fOrderModel.get(k).prod_code
                            close_para += "｜"
                            var bsText = fOrderModel.get(k).sale_type
                            if (bsText.indexOf("买") >= 0)
                                close_para += "b"
                            else
                                close_para += "s"
                            close_para += "｜"
                            close_para += fOrderModel.get(k).price
                            close_para += "｜"
                            close_para += fOrderModel.get(k).amount
                            close_para += "｜∧"
                        }

                        if (close_para.length > 0) {
                            tryCalcRisk = g_MainQuo.tryCalcRiskInfo(acctNo,
                                                                    close_para)
                        } else
                            tryCalcRisk = null
                    }
                }
            }
        }
        RowLayout {
            anchors.left: parent.left
            anchors.leftMargin: 5
            anchors.right: parent.right
            anchors.rightMargin: 10
            anchors.bottom: parent.bottom
            anchors.bottomMargin: 10
            spacing: 1
            //            Layout.preferredHeight: 50
            ColumnLayout {
                anchors.left: parent.left
                anchors.leftMargin: 5
                anchors.top: parent.top
                anchors.topMargin: 5
                anchors.bottom: parent.bottom
                anchors.bottomMargin: 5
                anchors.right: parent.right
                anchors.rightMargin: (parent.width * 3 / 4) + 5
                //                Layout.preferredWidth: parent.width / 4
                NameValue {
                    name: "风控可用" + colon
                    value: tryCalcRisk === null ? "" : tryCalcRisk.get(
                                                      "curr_bal")
                    Layout.alignment: Qt.AlignLeft
                }
                NameValue {
                    name: "浮动盈亏" + colon
                    value: tryCalcRisk === null ? "" : tryCalcRisk.get(
                                                      "float_surplus")
                    Layout.alignment: Qt.AlignLeft
                }
                NameValue {
                    name: "仍需追保金额" + colon
                    value: tryCalcRisk === null ? "" : tryCalcRisk.get(
                                                      "call_debt")
                    Layout.alignment: Qt.AlignLeft
                }
            }
            ColumnLayout {
                anchors.left: parent.left
                anchors.leftMargin: (parent.width / 4) + 5
                anchors.top: parent.top
                anchors.topMargin: 5
                anchors.bottom: parent.bottom
                anchors.bottomMargin: 5
                anchors.right: parent.right
                anchors.rightMargin: (parent.width * 2 / 4) + 5
                //                Layout.preferredWidth: parent.width / 4
                NameValue {
                    name: "交易所保证金" + colon
                    value: tryCalcRisk === null ? "" : tryCalcRisk.get(
                                                      "margin_exch")
                    Layout.alignment: Qt.AlignLeft
                }
                NameValue {
                    name: "会员保证金" + colon
                    value: tryCalcRisk === null ? "" : tryCalcRisk.get(
                                                      "margin_mem")
                    Layout.alignment: Qt.AlignLeft
                }
                NameValue {
                    name: "总保证金" + colon
                    value: tryCalcRisk === null ? "" : tryCalcRisk.get(
                                                      "margin_total")
                    Layout.alignment: Qt.AlignLeft
                }
            }
            ColumnLayout {
                anchors.left: parent.left
                anchors.leftMargin: (parent.width * 2 / 4) + 5
                anchors.top: parent.top
                anchors.topMargin: 5
                anchors.bottom: parent.bottom
                anchors.bottomMargin: 5
                anchors.right: parent.right
                anchors.rightMargin: (parent.width * 1 / 4) + 5
                //                Layout.preferredWidth: parent.width / 4
                NameValue {
                    name: "风险度1" + colon
                    value: tryCalcRisk === null ? "" : tryCalcRisk.get(
                                                      "risk_degree1")
                    Layout.alignment: Qt.AlignLeft
                }
                NameValue {
                    name: "风险度2" + colon
                    value: tryCalcRisk === null ? "" : tryCalcRisk.get(
                                                      "risk_degree2")
                    Layout.alignment: Qt.AlignLeft
                }
                NameValue {
                    name: "风险等级" + colon
                    value: tryCalcRisk === null ? "" : tryCalcRisk.get(
                                                      "risk_grade")
                    Layout.alignment: Qt.AlignLeft
                }
            }
        }
        Item {
            Layout.preferredHeight: 10 //补救
        }

        //        Component.onCompleted: {
        //            console.log("acctNo:" + acctNo)
        //            custDetail2 = g_MainQuo.getCustDetail(acctNo)
        //            freshFundRisk()
        //        }
    }
    Button {
        text: "关闭"
        anchors.right: parent.right
        anchors.rightMargin: 25
        anchors.bottom: parent.bottom
        anchors.bottomMargin: 10
        onClicked: closeTab(tabName)
    }
    function freshFundRisk() {
        posi_info.clear()
        store_info.clear()
        prodModel.clear()

        covDirModel.clear()
        if (custDetail2.get("acct_no") !== "") {
            var nPosInfoSize = custDetail2.getAlmSize("alm_posi_info")
            console.log("nPosInfoSize:" + nPosInfoSize)
            for (var i = 0; i < nPosInfoSize; ++i) {
                posi_info.append({
                                     ProdCode: custDetail2.getAlmString(
                                                   "alm_posi_info", i, 0),
                                     CurrLongAmt: custDetail2.getAlmString(
                                                      "alm_posi_info", i, 1),
                                     LongAvg: custDetail2.getAlmString(
                                                  "alm_posi_info", i, 2),
                                     LongOpenAvg: custDetail2.getAlmString(
                                                      "alm_posi_info", i, 3),
                                     CurrShortAmt: custDetail2.getAlmString(
                                                       "alm_posi_info", i, 4),
                                     ShortAvg: custDetail2.getAlmString(
                                                   "alm_posi_info", i, 5),
                                     ShortOpenAvg: custDetail2.getAlmString(
                                                       "alm_posi_info", i, 6),
                                     Surplus: custDetail2.getAlmString(
                                                  "alm_posi_info", i, 7),
                                     CurrPrice: custDetail2.getAlmString(
                                                    "alm_posi_info", i, 8)
                                 })
                prodModel.append({
                                     text: custDetail2.getAlmString(
                                               "alm_posi_info", i, 0)
                                 })
            }

            var nStoreSize = custDetail2.getAlmSize("alm_stor_info")
            for (var k = 0; k < nStoreSize; ++k) {
                store_info.append({
                                      VarietyId: custDetail2.getAlmString(
                                                     "alm_stor_info", k, 0),
                                      CurrAmt: custDetail2.getAlmString(
                                                   "alm_stor_info", k, 1),
                                      CurrCanUse: custDetail2.getAlmString(
                                                      "alm_stor_info", k, 2),
                                      AppFroz: custDetail2.getAlmString(
                                                   "alm_stor_info", k, 3)
                                  })
            }
        }

        freshCovBuySell()
        if (prodModel.count > 0) {
            prod_Code.currentIndex = 0
            cov_Posi.currentIndex = 0
        } else {
            prod_Code.currentIndex = -1
            cov_Posi.currentIndex = -1
        }
    }

    function freshCovBuySell() {
        if (custDetail2 == null)
            return
        var nPosInfoSize = custDetail2.getAlmSize("alm_posi_info")
        covDirModel.clear()
        for (var i = 0; i < nPosInfoSize; ++i) {
            var prod = custDetail2.getAlmString("alm_posi_info", i, 0)
            if (prod === prod_Code.currentText) {
                var longAmt = custDetail2.getAlmString("alm_posi_info", i, 1)
                var shortAmt = custDetail2.getAlmString("alm_posi_info", i, 4)
                console.log("longAmt:" + longAmt + " shortAmt:" + shortAmt)
                if (longAmt > 0)
                    covDirModel.append({
                                           text: "卖/平多"
                                       })
                if (shortAmt > 0)
                    covDirModel.append({
                                           text: "买/平空"
                                       })
            }
        }

        console.log("buysell drop size=" + covDirModel.count)
    }
    function createID(len) {
        var seqID = parseInt(Math.pow(10, len) * Math.random()).toString()

        var addCount = len - seqID.length
        for (var i = 0; i < addCount; ++i) {
            seqID += "1"
        }
        return seqID
    }

    //未验证2018-8-6
    function queryCovOrder() {
        covOrderRsp = g_MainQuo.queryPartMatchCovOrder("#acct_no=" + acctNo)
        var almName = "f_order_result"
        var nOrderSize = covOrderRsp.getAlmSize(almName)
        covOrderModel.clear()
        for (var k = 0; k < nOrderSize; ++k) {
            covOrderModel.append({
                                     OrderNo: covOrderRsp.getAlmString(almName,
                                                                       k, 0),
                                     ProcCode: covOrderRsp.getAlmString(
                                                   almName, k, 1),
                                     BS: covOrderRsp.getAlmString(almName, k,
                                                                  2),
                                     EntrPrice: covOrderRsp.getAlmString(
                                                    almName, k, 3),
                                     EntrAmount: covOrderRsp.getAlmString(
                                                     almName, k, 4),
                                     ExchAmount: covOrderRsp.getAlmString(
                                                     almName, k, 5),
                                     OrderState: covOrderRsp.getAlmString(
                                                     almName, k, 6),
                                     CovType: covOrderRsp.getAlmString(almName,
                                                                       k, 7),
                                     TellId: covOrderRsp.getAlmString(almName,
                                                                      k, 8)
                                 })
        }
    }

    ListModel {
        id: posi_info //持仓列表
    }
    ListModel {
        id: store_info //库存列表
    }
    ListModel {
        id: prodModel //合约下拉
    }
    ListModel {
        id: covDirModel //平仓方向下拉
    }

    ListModel {
        id: covOrderModel //平仓报单
    }
}
